package com.zy.server.service.impl;

import com.zy.config.RedisKeyConfig;
import com.zy.dto.SmsCodeDto;
import com.zy.server.entity.Smslog;
import com.zy.server.dao.SmslogMapper;
import com.zy.server.service.SmslogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.server.util.AliSmsUtil;
import com.zy.third.JedisUtil;
import com.zy.util.NumRandomUtil;
import com.zy.util.StrUtil;
import com.zy.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张鑫
 * @since 2020-11-27
 */
@Service
public class SmslogServiceImpl extends ServiceImpl<SmslogMapper, Smslog> implements SmslogService {

    @Autowired
    private SmslogMapper smslogMapper;

    // 发送短信验证码
    @Override
    public R sendCode(String phone) {
        // 校验参数
        if (StrUtil.checkNoEmpty(phone)) {

            // 判断是否符合手机号
            if (phone.matches("[1][3-9][0-9]{9}")) {
                // 生成随机验证码
                int code = NumRandomUtil.randomNum(6);

                // 发送短信验证码
                if (AliSmsUtil.sendSmsCode(phone, code)) {

                    // 存储短信验证码，用redis，他快，可以设置有效期，用String
                    JedisUtil.getInstance().addStrEx(RedisKeyConfig.SMS_RCODE+phone,code+"",RedisKeyConfig.SMS_RTIME);

                    // 记录发送的短信日志
                    Smslog smslog = new Smslog();
                    smslog.setPhone(phone);
                    smslog.setFlag(1);
                    smslog.setContent("本次发送的验证码为：" + code);
                    smslogMapper.insertSms(smslog);
                    return R.ok();

                }
            }
        }
        return R.fail("亲，请检查参数");
    }

    // 校验验证码
    @Override
    public R checkCode(SmsCodeDto smsCodeDto) {
        if (smsCodeDto != null) {
            if (StrUtil.checkNoEmpty(smsCodeDto.getPhone(), smsCodeDto.getCode()+"")) {
                String key = RedisKeyConfig.SMS_RCODE + smsCodeDto.getPhone();
                System.out.println(key);
                if (JedisUtil.getInstance().ishave(key)) {
                    if (JedisUtil.getInstance().getStr(key).equals(smsCodeDto.getCode())) {
                        // 验证通过
                        // 验证只要通过就删除
                        JedisUtil.getInstance().delKeys(key);
                        return R.ok();
                    }
                }
            }
        }
        return R.fail();
    }
}
